
package com.feib.soeasy.action;

import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.StringReader;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

import net.sourceforge.stripes.action.DefaultHandler;
import net.sourceforge.stripes.action.DontBind;
import net.sourceforge.stripes.action.ForwardResolution;
import net.sourceforge.stripes.action.Resolution;
import net.sourceforge.stripes.action.StreamingResolution;
import net.sourceforge.stripes.integration.spring.SpringBean;
import net.sourceforge.stripes.validation.DateTypeConverter;
import net.sourceforge.stripes.validation.LocalizableError;
import net.sourceforge.stripes.validation.SimpleError;
import net.sourceforge.stripes.validation.Validate;
import net.sourceforge.stripes.validation.ValidationErrors;

import com.feib.soeasy.model.Group;
import com.feib.soeasy.model.Payment;
import com.feib.soeasy.pagination.PaginatedList;
import com.feib.soeasy.service.GroupService;
import com.feib.soeasy.service.Soez5005Service;
import com.feib.soeasy.util.UserUtil;


/**
 * @title (#)Soez5005ActionBean.java<br>
 * @description <br>
 * @author Jimmy Liu<br>
 * @version 1.0.0 2010/11/25
 * @copyright Far Eastern International Bank Copyright (c) 2010<br>
 * @2011/3/19 create by Jimmy Liu<br>
 */
public class Soez5005ActionBean extends BaseActionBean {


    private static final String DEFAULT_JSP = "/WEB-INF/views/soez5005/soez5005.jsp";
    
    /**
     * 業者代號查詢畫面
     */
    private static final String AJAX_QUERY_GROUP_JSP = "/WEB-INF/views/soez5005/groupPopUpList.jsp";

    
    private Payment qryPayment;
    
    /**
     * 查詢條件
     * 資料期間基礎：1: 銷帳日期  2:實際繳款日。
     */
    private Integer qryDateType;
    
    /**
     * 查詢條件
     * 資料期間起
     */
    @Validate( converter=DateTypeConverter.class)
    private Date qryDateFrom;

    /**
     * 查詢條件
     * 資料期間迄
     */
    @Validate( converter=DateTypeConverter.class)
    private Date qryDateTo;
    
    /**
     * 統計表查詢結果
     */
    private List<Map<String, Object>> queryResult;

    
    /**
     * 查詢條件
     * 帳單業者
     */
    private Group qryGroup;
    
    /**
     * 帳單業者查詢結果
     */
    private PaginatedList<Group> queryGroupResult;
    
    @SpringBean("soez5005Service")
    private Soez5005Service soez5005Service;
    
    @SpringBean("groupService")
    private GroupService groupService;
    
    @DontBind
    @DefaultHandler
    public Resolution doDefault()
    {
        logger.debug("Enter doDefault mehtod.");
        try {
            Calendar cal = Calendar.getInstance();
            cal.add(Calendar.DATE, -1); 
            qryDateTo = cal.getTime();
       //     cal.add(Calendar.MONTH, -1);
            qryDateFrom = cal.getTime();
        }
        catch (Exception e) {
        }
        return new ForwardResolution(DEFAULT_JSP); 
    }
    
    public Resolution doAjaxQuery()
    {
        logger.debug("Enter doAjaxQuery mehtod.");
        try {
            if (null == qryDateType || 2 != qryDateType.intValue())
                qryDateType = new Integer(1);
            
            if (null == this.qryPayment)
                this.qryPayment = new Payment();

            //如果不是銀行端，則查詢條件要加入帳單業者限制
            if (!UserUtil.isBankGroup())
            {
                this.qryPayment.setGroup(UserUtil.getUserGroup());
            }
            else
                this.qryPayment.setGroup(this.groupService.findByExactGroupNo(this.qryPayment.getGroup().getGroupNo()));
          
             // queryResult = this.soez5005Service.queryForStatisticsList(this.qryPayment.getGroup(), this.qryDateType, this.qryDateFrom, this.qryDateTo);
            String message = this.soez5005Service.doExportGroupStatisticsHtml(this.qryPayment.getGroup(), this.qryDateType, this.qryDateFrom, this.qryDateTo);
            StreamingResolution resolution = new StreamingResolution("text/html", new StringReader(message.toString()));
            resolution.setCharacterEncoding("UTF-8");
            return resolution;
            
            
        }
        catch (Exception e) {
            logger.error("帳單通路統計表(月)錯誤(Soez5005ActionBean.doAjaxQuery): {}",e);

            // 轉換錯誤訊息
            ValidationErrors errors = new ValidationErrors();
            errors.addGlobalError(new LocalizableError("doAjaxQuery.exception") );
            getContext().setValidationErrors(errors);
            // 回傳 錯誤 HTML fragments
            return super.errorsToHtmlStreams(errors);
            
        }
        
    }
    
    
    
    /**
     * 下載Excel
     * @return
     */
    public Resolution doAjaxDownloadExcelFile()
    {
        logger.debug("Enter doAjaxDownloadExcelFile mehtod.");
        try {
            if (null == qryDateType || 2 != qryDateType.intValue())
                qryDateType = new Integer(1);
            
            if (null == this.qryPayment)
                this.qryPayment = new Payment();

            //如果不是銀行端，則查詢條件要加入帳單業者限制
            if (!UserUtil.isBankGroup())
            {
                this.qryPayment.setGroup(UserUtil.getUserGroup());
            }
            else
                this.qryPayment.setGroup(this.groupService.findByExactGroupNo(this.qryPayment.getGroup().getGroupNo()));
            
            String downloadFilePath = this.soez5005Service.doExportGroupStatisticsXls(this.qryPayment.getGroup(), this.qryDateType, this.qryDateFrom, this.qryDateTo);
            if (null == downloadFilePath)
            {
                // 查無資料
            }
            
            File downloadFile = new File(downloadFilePath);
            byte[] bytes = new byte[(int)downloadFile.length()];
            
            BufferedInputStream bufferedInputStream = 
                new BufferedInputStream(new FileInputStream(downloadFile)); 

            bufferedInputStream.read(bytes);

            ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes);
            inputStream.close();
            bufferedInputStream.close();
            // 黃郁珊 依問題單修改檔案名稱
            String isoFileName = new String("銀行入帳統計查詢.xls".getBytes("MS950"), "ISO8859-1");

            StreamingResolution streamingResolution = new StreamingResolution( 
                            "application/vnd.ms-excel",inputStream).setFilename(isoFileName);

            return streamingResolution;
        }
        catch (Exception e) {
            logger.error("", e);
        }
        return new ForwardResolution(DEFAULT_JSP); 
    }
    
    
     
    

    
    
    
    /**
     * 帳單業者查詢
     * @return
     */
    public Resolution doAjaxQueryGroups()
    {
        logger.debug("Enter doAjaxQueryGroups mehtod.");
        try {
            //如果不是銀行端，則查詢條件要加入帳單業者限制
            if (!UserUtil.isBankGroup())
            {
                throw new Exception("No Authority");
            }
            

            //USER未輸入查詢條件，所以查詢物件會是NULL(查詢物件不可為NULL)
            if (null == qryGroup)
                qryGroup = new Group();

            //呼叫服務查詢
            queryGroupResult = groupService.queryByGroupExcludeBank(qryGroup, queryGroupResult);
        }
        catch (Exception e) {
            logger.error("帳單通路統計表-帳單業者查詢錯誤(Soez5005ActionBean.doAjaxQueryGroups):", e);

            // 轉換錯誤訊息
            ValidationErrors errors = new ValidationErrors();
            errors.addGlobalError(new SimpleError("查詢錯誤！"));
            getContext().setValidationErrors(errors);
            // 回傳 錯誤 HTML fragments
            return super.errorsToHtmlStreams(errors);
        }

        return new ForwardResolution(AJAX_QUERY_GROUP_JSP);
    }

    
    
    /**
     * @return the qryPayment
     */
    public Payment getQryPayment() {
        return qryPayment;
    }

    
    /**
     * @param qryPayment the qryPayment to set
     */
    public void setQryPayment(Payment qryPayment) {
        this.qryPayment = qryPayment;
    }

    
    /**
     * @return the queryResult
     */
    public List<Map<String, Object>> getQueryResult() {
        return queryResult;
    }

    
    /**
     * @param queryResult the queryResult to set
     */
    public void setQueryResult(List<Map<String, Object>> queryResult) {
        this.queryResult = queryResult;
    }

    
    /**
     * @return the queryGroupResult
     */
    public PaginatedList<Group> getQueryGroupResult() {
        return queryGroupResult;
    }

    
    /**
     * @param queryGroupResult the queryGroupResult to set
     */
    public void setQueryGroupResult(PaginatedList<Group> queryGroupResult) {
        this.queryGroupResult = queryGroupResult;
    }

    /**
     * @return the qryDateType
     */
    public Integer getQryDateType() {
        return qryDateType;
    }

    
    /**
     * @param qryDateType the qryDateType to set
     */
    public void setQryDateType(Integer qryDateType) {
        this.qryDateType = qryDateType;
    }

    
    /**
     * @return the qryDateFrom
     */
    public Date getQryDateFrom() {
        return qryDateFrom;
    }

    
    /**
     * @param qryDateFrom the qryDateFrom to set
     */
    public void setQryDateFrom(Date qryDateFrom) {
        this.qryDateFrom = qryDateFrom;
    }

    
    /**
     * @return the qryDateTo
     */
    public Date getQryDateTo() {
        return qryDateTo;
    }

    
    /**
     * @param qryDateTo the qryDateTo to set
     */
    public void setQryDateTo(Date qryDateTo) {
        this.qryDateTo = qryDateTo;
    }

    
    /**
     * @return the qryGroup
     */
    public Group getQryGroup() {
        return qryGroup;
    }

    
    /**
     * @param qryGroup the qryGroup to set
     */
    public void setQryGroup(Group qryGroup) {
        this.qryGroup = qryGroup;
    }
}
